package grammar;

import grammar.perspective.CanNotLoadGrammarOnScreenException;
import grammar.perspective.GrammarHasNotSyntaxAssociatedException;
import grammar.perspective.GrammarNotExistException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

import DTO.Grammar;
import bd.configuration.MySql;

public class GrammarRepository {
	public static final String GRAMMAR_COLUMN_ID = "ID";
	public static final String GRAMMAR_COLUMN_SINTAX = "SYNTAX";
	public static final String GRAMMAR_COLUMN_TIMESTAMP = "CREATION_TIME";
	public static final String GRAMMAR_COLUMN_IS_ACTIVE = "IS_ACTIVE";

	private static String SELECT_LAST_GRAMMAR = "SELECT * FROM aspect_library.grammar where is_active like '1' order by creation_time desc";
	private static String INSERT_GRAMMAR = "INSERT INTO aspect_library.grammar (`syntax`,`is_active`, `creation_time`) VALUES (?, '0', current_timestamp)";
	private static String UPDATE_GRAMMAR = "UPDATE aspect_library.grammar SET syntax = ?, is_active = 0, creation_time = current_timestamp WHERE id = ?";

	public Grammar getGrammar() throws SQLException, CanNotLoadGrammarOnScreenException{
		Connection con = MySql.getConnection();
		Statement stmt = null;
		ResultSet rs = null;

		String syntax = null;
		Timestamp timeStamp = null;

		stmt = con.createStatement();

		rs = stmt.executeQuery(SELECT_LAST_GRAMMAR);
		if(rs.next()){
			syntax = rs.getString(GRAMMAR_COLUMN_SINTAX);
			timeStamp = rs.getTimestamp(GRAMMAR_COLUMN_TIMESTAMP);
		}

		con.close();

		if(syntax==null){
			throw new CanNotLoadGrammarOnScreenException();
		}

		return new Grammar(syntax,timeStamp);
	}

	public void setGrammar(Grammar grammar) throws SQLException, GrammarNotExistException, GrammarHasNotSyntaxAssociatedException{
		if(grammar.getSyntax()!=null && !grammar.getSyntax().equals("") && !grammar.getSyntax().equals(" ")){
			Connection con =  MySql.getConnection();
			PreparedStatement ps = null;
			ps = con.prepareStatement(INSERT_GRAMMAR);

			ps.setString(1, grammar.getSyntax());

			int rows = ps.executeUpdate();
			if (rows <= 0) {
				throw new GrammarNotExistException();
			}
			con.close();

		}else{
			throw new GrammarHasNotSyntaxAssociatedException();
		}
	}

	/* Consultas: */

	//SELECT_LAST_GRAMMAR
	/* SELECT id, syntax, is_active, creation_time
	FROM `aspect_library`.`grammar`
	where is_active like '1' order by creation_time desc;*/

	//UPDATE_GRAMMAR
	/* UPDATE `aspect_library`.`grammar`
	SET
	syntax = 'x', is_active = 0, creation_time = current_timestamp
	WHERE id = 2; */

	//INSERT GRAMMAR
	/*
	 INSERT INTO `aspect_library`.`grammar`
	(`syntax`,`is_active`, `creation_time`)
	VALUES
	(
	'aaaaaa',
	'0',
	current_timestamp
	);

	 */
}
